package com.ndp.fb.util;

import com.ndp.fb.enums.publish.BillingEvent;
import com.ndp.fb.enums.targetingspec.PageType;
import org.apache.commons.lang3.RandomUtils;

import java.util.List;


/**
 * 解决GA追踪码里面明文的问题，对版位，广告形式和出价进行二次编码
 *
 * Created by hunk.qin on 2016/5/3.
 */
public class GATrackEncoder {

    private static char [] qaz={'Q','A','Z'};
    private static char [] wsx={'W','S','X'};
    private static char [] edc={'E','D','C'};
    private static char [] rfv={'R','F','V'};

    private static char [] asd={'A','S','D'};
    private static char [] bnm={'B','N','M'};
    /**
     * 3-移动版动态消息       对应字符---EDC
       4-Audience Network  对应字符—RFV
       2-桌面版动态消息       对应字符---WSX
       1-桌面版右边栏         对应字符---QAZ
        rachel 定义
     * @param pageTypes
     * @return
     */
    public static String placementEncoder(List<PageType> pageTypes){
        StringBuffer buffer=new StringBuffer();
        for (int i = 0; i <pageTypes.size() ; i++) {
            buffer.insert(i,getCharByPlacement(pageTypes.get(i)));
        }
        if(pageTypes.size()>=3){
           return  buffer.toString();
        }else{
            int polishingLength=3-pageTypes.size();
            int random=RandomUtils.nextInt(10*(polishingLength-1),(10*polishingLength)-1);
            int insertPosition=RandomUtils.nextInt(0,2);
            if(insertPosition==0){
                buffer.insert(0,String.valueOf(random));
            }else{
                buffer.insert(pageTypes.size(),String.valueOf(random));
            }
            return buffer.toString();
        }
    }

    /**
     * A：CPC 出价 ---对应字符 ASD
       B：CPM出价 ----对应字符 BNM
     * @param billingevent
     * @return
     */
    public static String billingEventEncoder(BillingEvent billingevent){
        StringBuffer buffer=new StringBuffer();
        if(billingevent.equals(BillingEvent.LINK_CLICKS)){
            buffer.insert(0,asd[RandomUtils.nextInt(0,3)]);
        }else if(billingevent.equals(BillingEvent.IMPRESSIONS)){
            buffer.insert(0,bnm[RandomUtils.nextInt(0,3)]);
        }
        int random=RandomUtils.nextInt(10,99);
        int insertPosition=RandomUtils.nextInt(0,2);
        if(insertPosition==0){
            buffer.insert(0,String.valueOf(random));
        }else{
            buffer.insert(1,String.valueOf(random));
        }
        return buffer.toString();
    }


    private static char  getCharByPlacement(PageType pageType){
        switch (pageType){
            case desktopfeed:
                return wsx[RandomUtils.nextInt(0,3)];
            case rightcolumn:
                return qaz[RandomUtils.nextInt(0,3)];
            case mobilefeed:
                return edc[RandomUtils.nextInt(0,3)];
            case mobileexternal:
                return rfv[RandomUtils.nextInt(0,3)];
            default:
                return 'X';
        }
    }
}
